package com.gu.reentrantLock;

import java.util.concurrent.TimeUnit;

/**
 * @Author: gusongliao
 * @Description: 死锁问题
 * @createDate 2023/05/28 14:11
 */
public class DeadLock {


    /**
     * 打印结果
     * A 持有锁a，试图获取锁b
     * B 持有锁b，试图获取锁a
     * @param args
     */
    public static void main(String[] args) {

        Object a = new Object();
        Object b = new Object();

        new Thread(() -> {
            synchronized (a) {
                System.out.println(Thread.currentThread().getName() + " 持有锁a，试图获取锁b");

                // 防止时间过快没效果，等待
                try {
                    TimeUnit.SECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b) {
                    System.out.println(Thread.currentThread().getName() + " 获取锁b");
                }
            }
        }, "A").start();

        new Thread(() -> {
            synchronized (b) {
                System.out.println(Thread.currentThread().getName() + " 持有锁b，试图获取锁a");

                // 防止时间过快没效果，等待
                try {
                    TimeUnit.SECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (a) {
                    System.out.println(Thread.currentThread().getName() + " 获取锁a");
                }
            }
        }, "B").start();

    }

}
